import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:openim_common/openim_common.dart';

class LocationPickerView extends StatefulWidget {
  final LatLng? initialPosition;
  final String? initialAddress;

  const LocationPickerView({
    Key? key,
    this.initialPosition,
    this.initialAddress,
  }) : super(key: key);

  @override
  State<LocationPickerView> createState() => _LocationPickerViewState();
}

class _LocationPickerViewState extends State<LocationPickerView> {
  late MapController _mapController;
  LatLng? _selectedPosition;
  String _selectedAddress = '';
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _mapController = MapController();
    
    if (widget.initialPosition != null) {
      _selectedPosition = widget.initialPosition;
      _selectedAddress = widget.initialAddress ?? '';
    } else {
      _getCurrentLocation();
    }
  }

  Future<void> _getCurrentLocation() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 检查定位权限
      LocationPermission permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
      }

      if (permission == LocationPermission.denied || 
          permission == LocationPermission.deniedForever) {
        // 使用默认位置（北京）
        _selectedPosition = LatLng(39.9042, 116.4074);
        _selectedAddress = '北京市';
        IMViews.showToast('定位权限被拒绝，使用默认位置');
      } else {
        Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high,
        );
        _selectedPosition = LatLng(position.latitude, position.longitude);
        await _getAddressFromPosition(_selectedPosition!);
      }
    } catch (e) {
      // 使用默认位置
      _selectedPosition = LatLng(39.9042, 116.4074);
      _selectedAddress = '北京市';
      IMViews.showToast('获取位置失败，使用默认位置');
    }

    setState(() {
      _isLoading = false;
    });

    if (_selectedPosition != null) {
      _mapController.move(_selectedPosition!, 15.0);
    }
  }

  Future<void> _getAddressFromPosition(LatLng position) async {
    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(
        position.latitude,
        position.longitude,
      );

      if (placemarks.isNotEmpty) {
        Placemark place = placemarks.first;
        _selectedAddress = '${place.country ?? ''} ${place.administrativeArea ?? ''} ${place.locality ?? ''} ${place.street ?? ''}'.trim();
        if (_selectedAddress.isEmpty) {
          _selectedAddress = '未知位置';
        }
      }
    } catch (e) {
      _selectedAddress = '未知位置';
    }
  }

  void _onMapTap(TapPosition tapPosition, LatLng position) async {
    setState(() {
      _selectedPosition = position;
      _isLoading = true;
    });

    await _getAddressFromPosition(position);

    setState(() {
      _isLoading = false;
    });
  }

  void _confirmSelection() {
    if (_selectedPosition != null) {
      Get.back(result: {
        'position': _selectedPosition,
        'address': _selectedAddress,
        'latitude': _selectedPosition!.latitude,
        'longitude': _selectedPosition!.longitude,
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TitleBar.back(
        title: '选择位置',
        right: TextButton(
          onPressed: _selectedPosition != null ? _confirmSelection : null,
          child: Text(
            '确定',
            style: TextStyle(
              color: _selectedPosition != null ? Styles.c_0089FF : Styles.c_8E9AB0,
              fontSize: 16.sp,
            ),
          ),
        ),
      ),
      body: Stack(
        children: [
          FlutterMap(
            mapController: _mapController,
            options: MapOptions(
              initialCenter: _selectedPosition ?? LatLng(39.9042, 116.4074),
              initialZoom: 15.0,
              maxZoom: 18.0,
              onTap: _onMapTap,
            ),
            children: [
              TileLayer(
                urlTemplate: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                userAgentPackageName: '',
              ),
              if (_selectedPosition != null)
                MarkerLayer(
                  markers: [
                    Marker(
                      point: _selectedPosition!,
                      child: Icon(
                        Icons.location_on_sharp,
                        color: Styles.c_FF381F,
                        size: 40.w,
                      ),
                    ),
                  ],
                ),
            ],
          ),
          // 底部信息面板
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(16.r)),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '选中的位置',
                    style: Styles.ts_0C1C33_17sp_semibold,
                  ),
                  8.verticalSpace,
                  if (_isLoading)
                    Row(
                      children: [
                        SizedBox(
                          width: 16.w,
                          height: 16.w,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Styles.c_0089FF,
                          ),
                        ),
                        8.horizontalSpace,
                        Text('获取地址中...', style: Styles.ts_8E9AB0_14sp),
                      ],
                    )
                  else
                    Text(
                      _selectedAddress.isNotEmpty ? _selectedAddress : '未选择位置',
                      style: Styles.ts_0C1C33_14sp,
                    ),
                  if (_selectedPosition != null) ...[
                    4.verticalSpace,
                    Text(
                      '经度: ${_selectedPosition!.longitude.toStringAsFixed(6)}',
                      style: Styles.ts_8E9AB0_12sp,
                    ),
                    Text(
                      '纬度: ${_selectedPosition!.latitude.toStringAsFixed(6)}',
                      style: Styles.ts_8E9AB0_12sp,
                    ),
                  ],
                ],
              ),
            ),
          ),
          // 定位按钮
          Positioned(
            top: 16.h,
            right: 16.w,
            child: FloatingActionButton(
              mini: true,
              backgroundColor: Colors.white,
              onPressed: _getCurrentLocation,
              child: Icon(
                Icons.my_location,
                color: Styles.c_0089FF,
              ),
            ),
          ),
        ],
      ),
    );
  }
}